<?php
class EventsController extends AppController {

	var $name = 'Events';
	var $helpers = array('Html', 'Form', 'Javascript', 'Time');
	var $components = array('Filehandler', 'Image');
	var $uses = array('Event','Upcoming', 'Setting');
	
	var $external_enabled = false;
	
	// we need to separate out the ongoing events
	// and display them at the top of the month.
	// we also need to check to see if they
	// [] continue through the month (start date month < current month)
	// [] start this month (start date month == current month)
	// [] end during this month (end date month == current month)
	function index() {
		$this->Event->recursive = 1;
		$start_months = $this->Event->query("SELECT DATE_FORMAT(startdate, '%Y-%m') FROM events WHERE MONTH(startdate)>0 GROUP BY MONTH(startdate) ORDER BY startdate ASC");
		//$this->Event->findAll('GROUP BY MONTH(startdate)','MONTH(startdate)','startdate');
		$end_months = $this->Event->query("SELECT DATE_FORMAT(enddate, '%Y-%m') FROM events WHERE MONTH(enddate)>0 GROUP BY MONTH(enddate) ORDER BY enddate ASC");
		//$this->Event->findAll('GROUP BY MONTH(enddate)','CONCAT(YEAR(enddate),MONTH(enddate))','enddate');
		
		$allmonths = array_merge_recursive($start_months, $end_months);
		$unique_months = array_unique($this->__array_values_recursive($allmonths));
		
		//pr($unique_months);
		$events = $this->Event->findAll();
		
		foreach ($unique_months as $key => $month) {
			$current_month = date("Ym", strtotime($month."-01")); 
			foreach ($events as $event) {
				$startmonth = date("Ym", strtotime($event['Event']["startdate"]));
				if (isset ($event['Event']['enddate'])) {
					$endmonth = strtotime($event['Event']['enddate']);
				} else $endmonth = "0000-00-00";
				
				
				//if it's an ongoing event and it's 
				// end date is in this month, set 
				// it's display date to be it's end date
				if( ($event['Event']['type'] == "Ongoing")/* && ($current_month == $endmonth) */) {
					if ($current_month == $endmonth) {
					
					$event['Event']['display_date'] = $event['Event']['enddate'];
					$event_list[$event['Event']['enddate'] . $event['Event']['id']] = $event;
					}
					if ($current_month == $startmonth) {
						$event['Event']['display_date'] = $event['Event']['startdate'];
						$event_list[$event['Event']['startdate'] . $event['Event']['id']] = $event;
					}
				}
				elseif ($current_month == $startmonth) {
					
					$event['Event']['display_date'] = $event['Event']['startdate'];
					$event_list[$event['Event']['startdate'] . $event['Event']['id']] = $event;
				}
			}
		}
		
		ksort($event_list);
		//pr($event_list);
		$this->set('months',$unique_months);

		$this->set('events', $event_list);
	}

	function search() {
	
		$startsearch = strtotime($this->data['start_search']);
		$endsearch = strtotime($this->data['end_search']);
	
		$this->Event->recursive = 1;
		$start_months = $this->Event->query("SELECT DATE_FORMAT(startdate, '%Y-%m') FROM events WHERE MONTH(startdate)>0 GROUP BY MONTH(startdate) ORDER BY startdate ASC");
		//$this->Event->findAll('GROUP BY MONTH(startdate)','MONTH(startdate)','startdate');
		$end_months = $this->Event->query("SELECT DATE_FORMAT(enddate, '%Y-%m') FROM events WHERE MONTH(enddate)>0 GROUP BY MONTH(enddate) ORDER BY enddate ASC");
		//$this->Event->findAll('GROUP BY MONTH(enddate)','CONCAT(YEAR(enddate),MONTH(enddate))','enddate');
		
		$allmonths = array_merge_recursive($start_months, $end_months);
		$unique_months = array_unique($this->__array_values_recursive($allmonths));
		
		//pr($unique_months);
		$events = $this->Event->findAll();
		
		foreach ($unique_months as $key => $month) {
			$current_month = date("Ym", strtotime($month."-01")); 
			$this_month = null;
			foreach ($events as $event) {
				
				$startmonth = date("Ym", strtotime($event['Event']["startdate"]));
				$endmonth = date("Ym", strtotime($event['Event']["enddate"]));
				
				//if it's an ongoing event and it's 
				// end date is in this month, set 
				// it's display date to be it's end date
				if( ($event['Event']['type'] == "Ongoing") && ($current_month == $endmonth) ) {
					$event['Event']['display_date'] = $event['Event']['enddate'];
					$event_list[$event['Event']['enddate'] . $event['Event']['id']] = $event;
					
				}
				elseif ( ($event['Event']['type'] != "Ongoing") || ($current_month == $startmonth) ) {
					$event['Event']['display_date'] = $event['Event']['startdate'];
					$event_list[$event['Event']['startdate'] . $event['Event']['id']] = $event;
					
				}
				
				$date_string = strtotime($event['Event']['display_date']);
				$start_date_string = strtotime($event['Event']['startdate']);
				$end_date_string = strtotime($event['Event']['enddate']);
				
				
				if  ($current_month == date("Ym",$date_string)) {
				if (($event['Event']['type'] == "Ongoing") && ( date("Ymd", $end_date_string) <= date("Ymd",$endsearch) )) {
					if (date("Ym", $current_month) == date("Ym",$end_date_string) ){
						$this_month = $month;
					}
					elseif ( date("Ymd", $start_date_string) >= date("Ymd",$startsearch)  && ( date("Ymd", $end_date_string) <= date("Ymd",$endsearch)) ) {
						$this_month = $month;
					}
				} 
				elseif ( date("Ymd", $start_date_string) >= date("Ymd",$startsearch)  && ( date("Ymd", $end_date_string) <= date("Ymd",$endsearch)) && ( date("Ymd", $start_date_string) <= date("Ymd",$endsearch)) ) {
					$this_month = $month;
				}
				}
				
				
			}
			
			$display_months[] = $this_month;
		}
		
		//pr($display_months);
		
		ksort($event_list);
		//pr($event_list);
		$this->set('months',$display_months);
				
		$this->set('events', $event_list);
	}



	function view($id = null) {
		if(!$id) {
			$this->Session->setFlash('Invalid id for Event.');
			$this->redirect('/event/index');
		}
		$this->set('event', $this->Event->read(null, $id));
	}

	function admin_add() {
		
		$this->__init_external();
		
		$this->set('external_enabled',$this->external_enabled);
		
		if(empty($this->data)) {
			$this->set('contacts',$this->Event->getContactsList());
			$this->render();
		} else {
			$this->set('contacts',$this->Event->getContactsList());
			
			$this->cleanUpFields();
			$errors = "";
			//update image name
			if($this->Filehandler->upload('image', ROOT  . DS . APP_DIR . DS . WEBROOT_DIR . DS . 'img/detail/')) {
				$imageData = $this->Filehandler->getLastUploadInfo();
			 	$this->data["Event"]["image"]= $imageData['file_name'];
			
			} else $errors = 'Problem uploading the image: '. $this->Filehandler->errorMessage;
		
			if($this->data["Event"]["contact_id"] == "-1") {
				//save contact info too
				if($this->Event->Contact->save($this->data["Contact"])) 
					$this->data["Event"]["contact_id"] = $this->Event->Contact->getLastInsertID();
			}
		
			$errors .= $this->__publish_externally();
			
			if($this->Event->save($this->data)) {
								
				$this->Session->setFlash('The Event has been saved.' . $errors);
								
				//$this->redirect('/admin/events/index');
			} else {
				$this->Session->setFlash('Event did not save. ' . $errors);
			}
		}
	}


	
	function admin_index() {
		
		$this->__init_external();
		$this->set('external_enabled',$this->external_enabled);
		
		$this->Event->recursive = 1;
		$start_months = $this->Event->query("SELECT DATE_FORMAT(startdate, '%Y-%m') FROM events WHERE MONTH(startdate)>0 GROUP BY MONTH(startdate) ORDER BY startdate ASC");
		//$this->Event->findAll('GROUP BY MONTH(startdate)','MONTH(startdate)','startdate');
		$end_months = $this->Event->query("SELECT DATE_FORMAT(enddate, '%Y-%m') FROM events WHERE MONTH(enddate)>0 GROUP BY MONTH(enddate) ORDER BY enddate ASC");
		//$this->Event->findAll('GROUP BY MONTH(enddate)','CONCAT(YEAR(enddate),MONTH(enddate))','enddate');
		
		$allmonths = array_merge_recursive($start_months, $end_months);
		$unique_months = array_unique($this->__array_values_recursive($allmonths));
		
		//pr($unique_months);
		$events = $this->Event->findAll();
		
		foreach ($unique_months as $key => $month) {
			$current_month = date("Ym", strtotime($month."-01")); 
			foreach ($events as $event) {
				$startmonth = date("Ym", strtotime($event['Event']["startdate"]));
					if (isset ($event['Event']['enddate'])) {
						$endmonth = date("Ym", strtotime($event['Event']["enddate"]));
					} else $endmonth = "000000";
				
				
				//if it's an ongoing event and it's 
				// end date is in this month, set 
				// it's display date to be it's end date
				if( ($event['Event']['type'] == "Ongoing") && ($current_month == $endmonth) ) {
					$event['Event']['display_date'] = $event['Event']['enddate'];
					$event_list[$event['Event']['enddate'] . $event['Event']['id']] = $event;
				}
				elseif ($current_month == $startmonth) {
					$event['Event']['display_date'] = $event['Event']['startdate'];
					$event_list[$event['Event']['startdate'] . $event['Event']['id']] = $event;
				}
			}
		}
		
		ksort($event_list);
		//pr($event_list);
		$this->set('months',$unique_months);
		//$this->set('months', $this->Event->findAll('GROUP BY MONTH(startdate),','startdate','startdate'));
		
		// we need to separate out the ongoing events
		// and display them at the top of the page.
		// we also need to check to see if they
		// [] continue through the month (start date month < current month)

		// [] start this month (start date month == current month)
		// [] end during this month (end date month == current month)
		
		$this->set('events', $event_list);
	}

	function admin_view($id = null) {
		if(!$id) {
			$this->Session->setFlash('Invalid id for Event.');
			$this->redirect('/admin/event/index');
		}
		$this->set('event', $this->Event->read(null, $id));
	}

	function admin_edit($id = null) {
		
		$this->__init_external();
		$this->set('external_enabled',$this->external_enabled);
		if(empty($this->data)) {
			if(!$id) {
				$this->Session->setFlash('Invalid id for Event');
				$this->redirect('/admin/events/index');
			}
			$this->set('contacts',$this->Event->getContactsList());
			$this->data = $this->Event->read(null, $id);
		} else {
			$this->cleanUpFields();
			$errors = "";
			
			if($this->data["Event"]["usenoimageflag"] == "1") {
				$this->data["Event"]["image"] = "NULL";
			}
			
			//update image name
			if($this->Filehandler->upload('image', WWW_ROOT . 'img/detail/')) {
				$imageData = $this->Filehandler->getLastUploadInfo();
			 	$this->data["Event"]["image"]= $imageData['file_name'];
				$this->Image->resize('detail/'.$imageData['file_name'], 350, 250, false);
			
			} else $errors = ' '. $this->Filehandler->errorMessage;
			
			
		
			if($this->data["Event"]["contact_id"] == "-1") {
				//save contact info too
				if($this->Event->Contact->save($this->data["Contact"])) 
					$this->data["Event"]["contact_id"] = $this->Event->Contact->getLastInsertID();
			}
			
			$params = array();
			
			if ($this->data["Event"]["publishexternal"] == 0) 
				$params["personal"] = 1;
			else $params["personal"] = 0;
			
			// if the event has an external ID, then we 
			// should update it w/ new info
			// otherwise, if it's got no id but they 
			// chose to  publish it, use the add command
			// if the event has no external id and 
			// we're not adding it, we can just do nothing
			if ($this->data["Event"]["externalid"] != 0) {
				$params["event_id"] = $this->data["Event"]["externalid"];
				$errors .= $this->__publish_externally("edit", $params);
			} 
			elseif ($this->data["Event"]["publishexternal"] == 1)  
				$errors .= $this->__publish_externally("add", $params);
			
				
			
			if($this->Event->save($this->data)) {
				$this->Session->setFlash('The Event has been saved. ' . $errors);
				$this->redirect('/admin/events/index');
			} else {
				$this->Session->setFlash('Problems saving event.' . $errors);
			}
		}
	}

	function admin_copy($id = null) {
		
		$this->__init_external();
		$this->set('external_enabled',$this->external_enabled);
		
		if(empty($this->data)) {
			if(!$id) {
				$this->Session->setFlash('Invalid id for Event');
				$this->redirect('/admin/events/index');
			}
			$this->set('contacts',$this->Event->getContactsList());
			$this->data = $this->Event->read(null, $id);
		} else {
			$this->cleanUpFields();
			
			$errors = "";
			
			if($this->data["Event"]["usenoimageflag"] == "1") {
				$this->data["Event"]["image"] = "NULL";
			}
			
			//update image name
			if($this->Filehandler->upload('image', ROOT  . DS . APP_DIR . DS . WEBROOT_DIR . DS . 'img/detail/')) {
				$imageData = $this->Filehandler->getLastUploadInfo();
			 	$this->data["Event"]["image"]= $imageData['file_name'];
			
			} else $errors = ' '. $this->Filehandler->errorMessage;
		
			if($this->data["Event"]["contact_id"] == "-1") {
				//save contact info too
				if($this->Event->Contact->save($this->data["Contact"])) 
					$this->data["Event"]["contact_id"] = $this->Event->Contact->getLastInsertID();
			}
			
			$errors .= $this->__publish_externally();
			
			if($this->Event->save($this->data)) {
				$this->Session->setFlash('The Event has been saved. ' . $errors);
				$this->redirect('/admin/events/index');
			} else {
				$this->Session->setFlash('Problems saving event. ' . $errors);
			}
		}
	}
	

	function admin_delete($id = null) {
		$this->__init_external();
		$this->autoRender = false;
		if(!$id) {
			$this->Session->setFlash('Invalid id for Event');
			$this->redirect('/admin/events/index');
		}
		
		$errors ="";
		
		$params = array();
		$params["personal"] = 1;
		
		$event_id = $this->Event->field("externalid", "Event.id=$id");
		$this->data = $this->Event->read('', $id);
		
		if ($event_id != 0) {
			$params["event_id"] = $event_id;
			$errors = $this->__publish_externally("edit", $params);
			$errors .= " External event was hidden from public view.";
		} 		
		
		if($this->Event->del($id)) {
			$this->Session->setFlash('The Event deleted: id '.$id.'. ' . $errors);
			$this->redirect('/admin/events/index');
		}
	}
	
	function __array_values_recursive($array)
	{
	   $arrayValues = array();

	   foreach ($array as $value)
	   {
	       if (is_scalar($value) OR is_resource($value))
	       {
	             $arrayValues[] = $value;
	       }
	       elseif (is_array($value))
	       {
	             $arrayValues = array_merge($arrayValues, $this->__array_values_recursive($value));
	       }
	   }

	   return $arrayValues;
	}
	
	function __build_external_event()
	{
		// TODO: there's got to be a more elegant way of doing this...
		$params = array();
		if (isset($this->data["Event"]["title"])  && $this->data["Event"]["title"]) {
			$params["name"] = $this->data["Event"]["title"];
		}
		if (isset($this->data["Event"]["description"]) && $this->data["Event"]["description"] ) {
			$params["description"] = $this->data["Event"]["description"];
		}
		if (isset($this->data["Event"]["startdate"]) && $this->data["Event"]["startdate"]) {
			$params["start_date"] = $this->data["Event"]["startdate"];
		}
		if (isset($this->data["Event"]["enddate"]) && $this->data["Event"]["enddate"]) {
			if (str_replace("-", "", $this->data["Event"]["enddate"]) > 0) 
				$params["end_date"] = $this->data["Event"]["enddate"];
		}
		if (isset($this->data["Event"]["starttime"])) {
			if (str_replace(":", "", $this->data["Event"]["starttime"]) > 0) {
				$params["start_time"] = $this->data["Event"]["starttime"];
			}
		}
		if (isset($this->data["Event"]["endtime"])) {
			if (str_replace(":", "", $this->data["Event"]["endtime"]) > 0) {
				$params["end_time"] = $this->data["Event"]["endtime"];
			}
		}
		
		$params["selfpromotion"] = 1;
		
		return $params;
		
	}
	
	function __publish_externally($action="add", $additional_parameters = null )
	{
		$errors = "";
		// if we're going to send this to an outside service
		if ($this->data["Event"]["publishexternal"] || $action != "add") {
										
				//if we're set up to publish externally
				if($this->external_enabled) {
											
					$params = $this->__build_external_event();
					
					if (is_array($additional_parameters) && !empty($additional_parameters)){
						$params = array_merge($params, $additional_parameters);
					}
					
					switch ($action) {
						case 'edit':
							$publish_results = $this->Upcoming->edit($params);
							break;
						default:
							$publish_results = $this->Upcoming->add($params);
							break;
					}
															
					if($publish_results["stat"] == "ok") {
						$this->data["Event"]["externalid"] = $publish_results['event']["id"];
						$errors .= 'Successfully published event externally.';
					} else $errors .= 'Error publishing to external service: <pre>' . print_r($this->Upcoming->errorArray, true) . '</pre>';
				
				} else $errors .= 'Error publishing to external service: Invalid API key or auth token.';
				
		}
		
		return $errors;
	}
	
	function __init_external()
	{
		
		$api_key = $this->Setting->field("value", "Setting.key='upcoming_api_key'");
		$this->Upcoming->token = $this->Setting->field("value", "Setting.key='upcoming_auth_token'");
		$this->Upcoming->venue_id = $this->Setting->field("value", "Setting.key='venue_id'");
		$this->Upcoming->category_id = $this->Setting->field("value", "Setting.key='category_id'");
		
		$this->set('venue_id',$this->Upcoming->venue_id);
		$this->set('external_enabled',$this->external_enabled);
		
		if($api_key && $this->Upcoming->token) 
			$this->external_enabled = true;
			$this->Upcoming->options["api_key"] = $api_key;
	}

}
?>